<template>
    <div>
        <h1>商品分类</h1>
        <!-- 按钮 -->
        <el-button type="primary" icon="el-icon-plus" style="margin: 10px 0px;" @click="showDialog">
            添加
        </el-button>

        <el-table border style="width:100%" :data="list">
            <el-table-column label="序号" type="index" width="80px" align="center">
            </el-table-column>
            <el-table-column label="分类名称" prop="categoryName" align="center">
            </el-table-column>
            <el-table-column label="是否使用分类" prop="is_delete" align="center">
                <template slot-scope="{row,$index}">
                    {{ row.is_delete == 0 ? "是" : '否' }}
                </template>
            </el-table-column>
            <el-table-column label="操作" prop="prop" align="center">
                <!-- 形参必须为row，$index -->
                <template slot-scope="{row,$index}">
                    <el-button @click="updateCategoryState(row,1)" icon="el-icon-sort-down" type="danger" v-if="row.is_delete==0">下架分类</el-button>
                    <el-button @click="updateCategoryState(row,0)" icon="el-icon-sort-up" type="success" v-else>上架分类</el-button>
                    <el-button @click="updateCategory(row)" icon="el-icon-edit" type="warning">修改</el-button>
                    <el-button @click="deleteCategory(row)" icon="el-icon-delete" type="danger">删除</el-button>
                </template>
            </el-table-column>
        </el-table>


        <!-- 对话框-->
        <el-dialog :title="categoryForm.id ? '修改分类' : '添加分类'" :visible.sync="dialogFormVisible">
            <el-form style="width:80%" :model="categoryForm" :rules="rules" ref="ruleForm">
                <el-form-item label="分类名称" label-width="100px" prop="categoryName">
                    <el-input autocomplete="off" v-model="categoryForm.categoryName"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addOrUpdateCategory">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>


export default {
    name: 'tradeMark',
    data() {
        //自定义校验规则，给与下面表格验证使用
        var validateName = (rule, value, callback) => {
            //自定义校验规则
            if (value.length < 1 || value.length > 10) {
                callback(new Error('分类名称长度为1-10'))
            } else {
                callback();
            }
        };
        return {
            list: [],   //列表展示的数据
            dialogFormVisible: false,    //对话框显示隐藏熟悉
            categoryForm: {            //收集品牌信息
                categoryName: '',
            },
            //表单验证规则
            rules: {
                //品牌名称的验证规则
                categoryName: [
                    //required:前面多个星号 message:提示信息    trigger：用户行为触发验证(blur/change)
                    { required: true, message: '请输入分类名称', trigger: 'blur' },
                    //自定义规则
                    { validator: validateName, trigger: 'blur' }
                ],
            }
        };
    },
    mounted() {
        //页面挂载时获取品牌列表数据
        this.getCategoryList();
    },
    methods: {
        //获取分类列表数据方法
        async getCategoryList() {
            //修改当前页数
            //获取商品列表的接口
            let result = await this.$API.reqGetAllGoodCates();
            this.list = result.data.data
        },
        //点击添加品牌的按钮
        showDialog() {
            //显示对话框
            this.dialogFormVisible = true;
            //清空数据
            this.categoryForm = { categoryName: '' };
        },
        //点击修改某一个品牌d的按钮
        updateCategory(row) {
            //显示对话框
            this.dialogFormVisible = true;
            console.log(row);
            //row:当前品牌的信息
            this.categoryForm = { ...row }    //深拷贝，让修改时原来数据不变
        },
        //（添加分类||修改分类）
        addOrUpdateCategory() {
            //全部验证通过时
            this.$refs.ruleForm.validate(async (success) => {
                //如果全部字段符合条件
                if (success) {
                    this.dialogFormVisible = false;
                    //发请求（添加品牌||修改品牌）
                    let result = await this.$API.reqAddOrUpdateCategory(this.categoryForm);
                    if (result.data.code == 200) {
                        //弹出信息：添加品牌成功、修改品牌成功
                        this.$message({
                            type: 'success',
                            message: this.categoryForm.categoryId ? "修改分类成功" : "添加分类成功"
                        })
                        //添加或修改品牌成功后，再次获取品牌信息
                        this.getCategoryList();
                    } else {
                        //弹出信息：添加品牌失败、修改品牌失败
                        this.$message.error('分类更新失败')
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //删除分类
        deleteCategory(row) {
            //弹框
            this.$confirm(`你确定要删除${row.categoryName}?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let result = await this.$API.reqDeleteCategory(row.categoryId);
                //删除成功
                if (result.data.code == 200) {
                    //删除成功
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    //再次获取列表数据
                    this.getCategoryList();
                } else if (result.data.code == 201) {
                    //删除成功
                    this.$message({
                        type: 'error',
                        message: '该分类受保护不能删除!'
                    });
                } else {
                    //删除失败
                    this.$message.error('删除失败')
                }
            }).catch(() => {
                //取消删除
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //更新分类是否上架
        async updateCategoryState(row,flag){
            const res =await this.$API.reqUpdateCategoryIsDelete({categoryId:row.categoryId,type:flag})
            if (res.data.code == 200) {
                this.$message({
                    message:flag==1?'下架成功':'上架成功',
                    type: 'success'
                })
                row.is_delete = flag;
            }
        }
    }
};
</script>

<style  scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>